package com.yonyou.cyxdms.sysAuth.service.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yonyou.cyx.framework.bean.dto.framework.RestResultResponse;
import com.yonyou.cyx.framework.controller.base.BaseController;
import com.yonyou.cyxdms.sysAuth.service.dto.LoginLogPO;
import com.yonyou.cyxdms.sysAuth.service.dto.PhoneLoginDTO;
import com.yonyou.cyxdms.sysAuth.service.dto.UserDTO;
import com.yonyou.cyxdms.sysAuth.service.dto.user.EmployeeDTO;
import com.yonyou.cyxdms.sysAuth.service.dto.user.UserPO;
import com.yonyou.cyxdms.sysAuth.service.mapper.UserMapper;
import com.yonyou.cyxdms.sysAuth.service.service.RedisService;
import com.yonyou.cyxdms.sysAuth.service.service.manage.employee.EmployeeService;
import com.yonyou.cyxdms.sysAuth.service.utill.MD5Util;
import com.yonyou.cyxdms.sysAuth.service.utill.RandomValidateCodeUtil;
import com.yonyou.cyxdms.sysAuth.service.utill.StringUtils;
import com.yonyou.cyxdms.sysmanage.client.vo.employee.EmployeeVO;
import io.swagger.annotations.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * @author wanghongyu modify by shortwarren
 * 二版登陆
 */
@RestController
@RequestMapping("sysLogin/emp")
@Api(value = "系统模块SYS", tags = "系统模块SYS")
public class EmployeeController extends BaseController {

    private final Logger logger = LoggerFactory.getLogger(EmployeeController.class);
    private final String FLAG_ONE = "1";
    private final String DEVICE_PC = "PC";
    private final String DEVICE_APP = "app";
    private final String DEVICE_WECHAT = "wechat";
    private final String vDTMSSTATUES = "10011001";
    /**
     * 放到session中的key
     */
    private static final String RANDOMCODEKEY = "RANDOMVALIDATECODEKEY";

    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private RedisService redisService;

    @Autowired
    private UserMapper userMapper;


    @GetMapping("/getEmployees")
    public List<EmployeeVO> getEmployees(@ApiParam(name = "queryCondition", value = "查询条件", required = false) @RequestParam(required = false, defaultValue = "") String queryCondition) {
        return employeeService.getEmployees(queryCondition);
    }

    @GetMapping("/getEmployeesByEmployeeNO")
    public EmployeeVO getemployeesbyemployeeno(@RequestParam String appId, @RequestParam String employeeNO, @RequestParam String dealerCode) {
        return employeeService.getemployeesbyemployeeno(appId, employeeNO, dealerCode);
    }

    /**
     * @description：获取销售顾问列表
     * @author ：quankk
     * @date ：Created in 2019/1/8 15:13
     * @modified By：
     */
    @ApiOperation(value = "获取销售顾问列表", notes = "获取销售顾问列表")
    @GetMapping("/employeeByDealerCode")
    public List<EmployeeVO> employeeByDealerCode(@ApiParam(name = "appId", value = "appId", required = true) @RequestParam(required = true) String appId,
                                                 @ApiParam(name = "dealerCode", value = "经销商代码", required = true) @RequestParam(required = true) String dealerCode) {
        return employeeService.employeeByDealerCode(appId, dealerCode);
    }

    @ApiOperation(value = "模糊查询获取销售顾问编号", notes = "模糊查询获取销售顾问编号")
    @GetMapping("/getEmployeeNoByLikeEmployeeName")
    public List<EmployeeVO> getEmployeeNoByLikeEmployeeName(@ApiParam(name = "appId", value = "appId", required = true) @RequestParam(required = true) String appId,
                                                            @ApiParam(name = "dealerCode", value = "经销商代码", required = true) @RequestParam(required = true) String dealerCode,
                                                            @ApiParam(name = "employeeName", value = "销售顾问名称", required = true) @RequestParam(required = true) String employeeName) {
        return employeeService.getEmployeeNoByLikeEmployeeName(appId, dealerCode, employeeName);
    }

    /**
     * 根据角色查询销售顾问
     *
     * @param roleType
     * @return java.util.List<com.yonyou.cyxdms.basedata.client.domains.vo.EmployeeVO>
     * @author renwd
     * @since 2019/3/21
     */
    @ApiOperation(value = "根据角色查询销售顾问", notes = "根据角色查询销售顾问")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", required = true, dataType = "string", paramType = "header")
    })
    @GetMapping("/getEmployeesByPosition")
    public List<EmployeeVO> getEmployeesByPosition(Integer roleType) {
        return employeeService.getEmployeesByPosition(roleType);
    }

    /**
     * 用户名/手机号登陆
     *
     * @param empDto 入参
     * @return 首页用户信息
     */
    @ResponseBody
    @PostMapping(value = "/loginByNameOrPhone")
    @ApiOperation(value = "=====2版使用手机号/P码和密码登陆/微信OPID登陆=====")
    public Map<String, Object> loginByNameOrPhone(@RequestBody EmployeeDTO empDto, HttpSession session) throws DmsBizException {
        Map<String, Object> map = new HashMap<>(10);
        String vUser = empDto.getvLogin();
        String vPwd = empDto.getvPwd();
        String device = empDto.getDevice();
        String pwds = MD5Util.getEncryptedPwd(vPwd);
        logger.error("=====================入参信息：" + empDto.toString() + "==================");
        if (!DEVICE_WECHAT.equals(device)) {
            if (StringUtils.isNullOrEmpty(vUser) || StringUtils.isNullOrEmpty(pwds)) {
                throw new DmsBizException(501, "用户名或密码不可为空");
            }
        }
        //是否是手机号登陆
        String flag = "";
//        if (DEVICE_PC.equals(device)) {
//            flag = FLAG_ONE;
//        }

        if (vUser != null && vUser.length() == 11) {
            flag = FLAG_ONE;
            boolean bool = Pattern.matches("^[1][3-9][0-9]{9}$", vUser);
            if (!bool) {
                throw new DmsBizException(501, "手机号格式不对！");
            }
        }

        EmployeeDTO dto = employeeService.findEmpInfo(vUser);
        UserPO userpo = new UserPO();
        if (dto != null) {
            if ("0".equals(dto.getcBindState()) && dto.getvState() == 9) {
                throw new DmsBizException(900, "该账号注册申请已经提交，请联系网管审核！");
            }
            if ("0".equals(dto.getcLogin())) {
                throw new DmsBizException(900, "账号未注册！");
            }
        } else {
            throw new DmsBizException(900, "DTMS账户不存在！");
        }

        int failNum = dto.getnLoginFailNum();
        String inputStr = empDto.getImgCheck();
        logger.debug("图形验证码" + inputStr);

        if (inputStr != null && !"".equals(inputStr)) {
            //从session中获取验证码：后续改成redis
            String random = (String) redisService.get(RANDOMCODEKEY + vUser);
            System.out.print("redis12313131313123:" + random);
            logger.debug("session图形验证码" + random);
            if (random != null) {
                if (!inputStr.toUpperCase().equals(random.toUpperCase())) {
                    throw new DmsBizException(501, "验证码错误！");
                }
            } else {
                throw new DmsBizException(501, "验证码已过期！");
            }
        } else if (failNum >= 2 && "".equals(inputStr)) {
            throw new DmsBizException(501, "请输入验证码进行登陆！");
        }


        //初始密码登陆标识
        String isInit = "";
        if (dto != null) {
            if (dto.getcInitPWD() == 1) {
                //初始密码登陆
                isInit = FLAG_ONE;
            }
            int vState = dto.getvState();
            String vdtmsstatus = dto.getvDTMSStatus();
            if (!vDTMSSTATUES.equals(vdtmsstatus)) {
                throw new DmsBizException(900, "您的DTMS账户不可用");
            }
            if (FLAG_ONE.equals(flag) && FLAG_ONE.equals(dto.getcBindState())) {
                throw new DmsBizException(900, "您的账户未绑定手机号码");
            }
            //初始密码登陆
            if (FLAG_ONE.equals(isInit) && !DEVICE_WECHAT.equals(device)) {
                logger.error("====进入首次登陆校验====");
                checkEmp(vPwd, vUser, dto.getvInitPWD(), vState, dto.getnLoginFailNum(), dto.getUpdateOn());
            } else if (DEVICE_WECHAT.equals(device)) {
                logger.error("===========================手机、PC微信登陆不校验密码================================");
            } else {
                //正常密码登陆
                logger.error("====进入登陆校验====");
                checkEmp(vPwd, vUser, dto.getvPwd(), vState, dto.getnLoginFailNum(), dto.getUpdateOn());
            }

            QueryWrapper<UserPO> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("nEmployeeID", dto.getId());
            List<UserPO> userpo2 = userpo.selectList(queryWrapper);
            String res = this.checkLogin(userpo2.get(0).getvlogin());
            if (!"OK".equals(res)) {
                throw new DmsBizException(501, res);
            }

//            userLogin user = new userLogin();
//            user.setName(dto.getvLogin());
//            user.setDevice(device);
//            user.setPwd(vPwd);
//            user.setrEG_ID(empDto.getrEG_ID());
//            userLoginController.getLogin(user);

            List<UserDTO> tmUserList = employeeService.checkUser(dto.getId());
            String reg = empDto.getrEG_ID();

            if (tmUserList != null && tmUserList.size() > 0) {
                if (!StringUtils.isNullOrEmpty(reg)) {
                    employeeService.updatereg(tmUserList.get(0).getId(), reg);
                }
                LoginLogPO loginlogpo = new LoginLogPO();
                loginlogpo.setNdid(tmUserList.get(0).getNdid());
                loginlogpo.setEmpid(dto.getId());
                loginlogpo.setUserid(tmUserList.get(0).getId());
                loginlogpo.setvLogin(tmUserList.get(0).getvLogin());
                loginlogpo.setLoginTime(LocalDateTime.now());
                loginlogpo.setType("login");
                loginlogpo.insert();
                logger.info("登陆人员信息：{}", loginlogpo.toString());
                map = this.assembleReturn(tmUserList, device, dto);
            } else {
                throw new DmsBizException(501, "登录失败");
            }
        } else {
            throw new DmsBizException(900, "该账户不存在！");
        }
        return map;
    }

    /**
     * 手机号&&验证码登陆 APP端使用的接口
     *
     * @param phoneLoginDTO 入参 手机号，验证码
     * @return 首页用户信息
     */
    @ResponseBody
    @PostMapping(value = "/loginByPhoneAndVercode")
    @ApiOperation(value = "=====2版使用手机号和验证码登陆=====")
    public Map<String, Object> loginByPhoneAndVercode(@RequestBody PhoneLoginDTO phoneLoginDTO) throws DmsBizException {
        RestResultResponse res = new RestResultResponse();
        Map<String, Object> map = new HashMap<>(50);

        if (StringUtils.isNullOrEmpty(phoneLoginDTO.getPhoneNumber()) || StringUtils.isNullOrEmpty(phoneLoginDTO.getVerCode())) {
            throw new DmsBizException(501, "手机号或验证码不能为空！");
        }

        boolean bool = Pattern.matches("^[1][3-9][0-9]{9}$", phoneLoginDTO.getPhoneNumber());
        if (!bool) {
            throw new DmsBizException(501, "手机号格式输入错误！");
        }
//        VerificationDTO dtocheck = new VerificationDTO();
//        dtocheck.setvMobile(phoneLoginDTO.getPhoneNumber());
//        dtocheck.setvCode(phoneLoginDTO.getVerCode());
//        res = smsController.checkSMSCode(dtocheck);

        EmployeeDTO dto = employeeService.findEmpInfo(phoneLoginDTO.getPhoneNumber());
        logger.error("+++");
        if (dto != null) {
            String dtmsStatus = dto.getvDTMSStatus();

            if (FLAG_ONE.equals(dtmsStatus)) {
                throw new DmsBizException(900, "您的账户不可用");
            }

            if (FLAG_ONE.equals(dto.getcBindState())) {
                throw new DmsBizException(900, "您的账户未绑定手机号码");
            }

            UserPO userpo = new UserPO();
            QueryWrapper<UserPO> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("nEmployeeID", dto.getId());
            List<UserPO> userpo2 = userpo.selectList(queryWrapper);
            String res2 = this.checkLogin(userpo2.get(0).getvlogin());
            if (!"OK".equals(res2)) {
                throw new DmsBizException(501, res2);
            }
//            userLogin user = new userLogin();
//            user.setName(dto.getvLogin());
//            //暂时定这个接口只给手机端APP使用
//            user.setDevice("app");
//            user.setPwd(dto.getvPwd());
//            user.setrEG_ID(phoneLoginDTO.getrEG_ID());
//            userLoginController.getLogin(user);

            List<UserDTO> tmUserList = employeeService.checkUser(dto.getId());
            String reg = phoneLoginDTO.getrEG_ID();

            if (tmUserList != null && tmUserList.size() > 0) {
                if (!StringUtils.isNullOrEmpty(reg)) {
                    employeeService.updatereg(tmUserList.get(0).getId(), reg);
                }
                LoginLogPO loginlogpo = new LoginLogPO();
                loginlogpo.setNdid(tmUserList.get(0).getNdid());
                loginlogpo.setEmpid(dto.getId());
                loginlogpo.setUserid(tmUserList.get(0).getId());
                loginlogpo.setvLogin(tmUserList.get(0).getvLogin());
                loginlogpo.setLoginTime(LocalDateTime.now());
                loginlogpo.setType("login");
                loginlogpo.insert();
                logger.info("登陆人员信息：{}", loginlogpo.toString());
                map = this.assembleReturn(tmUserList, DEVICE_APP, dto);
            } else {
                throw new DmsBizException(501, "登录失败");
            }
        } else {
            throw new DmsBizException(900, "该账户不存在！");
        }
        return map;
    }

    /**
     * @param tmUserList 入参
     * @param device     设备
     * @return map
     */

    private Map<String, Object> assembleReturn(List<UserDTO> tmUserList, String device, EmployeeDTO dto) {
        Map<String, Object> map = new HashMap<>(50);
        map.put("device", device);
        map.put("nDID", tmUserList.get(0).getNdid());
        map.put("nBID", tmUserList.get(0).getNbid());
        map.put("vPerson", tmUserList.get(0).getvPerson());
        map.put("vPersonName", tmUserList.get(0).getvPersonName());
        map.put("vLogin", tmUserList.get(0).getvLogin());
        map.put("iD", tmUserList.get(0).getId());
        map.put("vOrgName", tmUserList.get(0).getvOrgName());
        map.put("vDutyName", tmUserList.get(0).getvDutyName());
        map.put("vDutyDetailName", tmUserList.get(0).getvDutyDetailName());
        map.put("nCustGroupId", tmUserList.get(0).getnCustGroupId());
        map.put("cMainBranch", tmUserList.get(0).getcMainBranch());
        map.put("vRoleName", tmUserList.get(0).getvRoleName());
        map.put("vRole", tmUserList.get(0).getvRole());
//        map.put("vWeChat",  tmUserList.get(0).getvWeChat());
        map.put("vHeadPath", tmUserList.get(0).getvHeadPath());
        map.put("cMain", tmUserList.get(0).getcMain());
        map.put("vUserVersion", tmUserList.get(0).getvUserVersion());
        map.put("vRoleVersion", tmUserList.get(0).getvRoleVersion());
        map.put("vUserRoleID", tmUserList.get(0).getvUserRoleID());
        map.put("vAddress", tmUserList.get(0).getvAddress());
        map.put("vDealerName", tmUserList.get(0).getvDealerName());
        map.put("vMobile", tmUserList.get(0).getvMobile());
        map.put("cInitPwd", dto.getcInitPWD());
        map.put("vWeChat", dto.getvAppOpenID());
        map.put("vWeChatPc", dto.getvWXOpenID());
        map.put("nickname", dto.getvWXNickName());
        map.put("cBindState", dto.getcBindState());

        return map;
    }

    /**
     * 忘记密码/立即修改密码
     *
     * @param empDto 入参
     * @return String
     */
    @ResponseBody
    @PostMapping(value = "/forGetPwd")
    @ApiOperation(value = "=====2版忘记密码/立即修改密码=====")
    public String forGetPwd(@RequestBody EmployeeDTO empDto) throws DmsBizException {
        String vMobile = empDto.getvMobile();
        String vPwd = empDto.getvPwd();
        //标识 1：立即修改密码
        String flag = empDto.getFlag();
        int phoneLength = 11;
        if (vMobile.length() != phoneLength) {
            logger.error("900：手机号不存在！");
            throw new DmsBizException(900, "手机号不存在！");
        }
        int result = employeeService.resetPwdByPhone(MD5Util.getEncryptedPwd(vPwd), vMobile, "", flag);
        //设置成非锁定状态（0：正常 1：锁定），错误次数为0
        employeeService.updateLoginFailNum(vMobile, 0, 0);
        String msg = "no";
        if (result > 0) {
            msg = "ok";
        }
        return msg;
    }

    /**
     * 重置密码 首次登陆修改密码或者基本信息界面修改密码
     *
     * @param empDto 入参
     * @return String
     */
    @ResponseBody
    @PostMapping(value = "/resetPwd")
    @ApiOperation(value = "=====2版重置密码=====")
    public RestResultResponse resetPwd(@RequestBody EmployeeDTO empDto) throws DmsBizException {
        RestResultResponse res = new RestResultResponse();
        String vMobile = empDto.getvMobile();
        String vPwd = empDto.getvPwd();
        String vPwdOld = empDto.getvPwdOld();
        boolean bool = Pattern.matches("^[1][3-9][0-9]{9}$", vMobile);
        if (!bool) {
            throw new DmsBizException(501, "手机号格式输入错误！");
        }
//        int phoneLength = 11;
//        if (vMobile.length() != phoneLength) {
//            throw new DmsBizException(900, "手机号不存在！");
//        }
        int result = employeeService.resetPwdByPhone(MD5Util.getEncryptedPwd(vPwd), vMobile, MD5Util.getEncryptedPwd(vPwdOld), "5");
        String msg = "no";
        if (result > 0) {
            res.setResultCode(200);
            res.setErrMsg("修改成功！");
        } else {
            res.setResultCode(400);
            res.setErrMsg("手机号或原密码错误，请重新确认！");
        }

        return res;
    }

    /**
     * APP 登陆后修改密码
     *
     * @param empDto 入参
     * @return String
     */
    @ResponseBody
    @PostMapping(value = "/modifyPwd")
    @ApiOperation(value = "=====2版app登陆后修改密码=====")
    public RestResultResponse modifyPwd(@RequestBody EmployeeDTO empDto) {
        RestResultResponse res = new RestResultResponse();
        String name = empDto.getName();
        String pwd = empDto.getPwd();
        String newPassword = empDto.getNewPassword();
        EmployeeDTO dto = employeeService.findEmpInfo(name);
        if (dto == null) {
            res.setResultCode(500);
            res.setErrMsg("账号不存在！");
        } else {
            int result = employeeService.resetPwdByPno(name, MD5Util.getEncryptedPwd(pwd), MD5Util.getEncryptedPwd(newPassword));
            if (result > 0) {
                res.setResultCode(200);
                res.setErrMsg("修改成功！");
            } else {
                res.setResultCode(400);
                res.setErrMsg("原密码错误，请确认！");
            }
        }

        return res;
    }

    /**
     * 查询锁定状态
     *
     * @param vMobile 入参
     * @return String
     */
    @ResponseBody
    @PostMapping(value = "/isBind")
    @ApiOperation(value = "=====2版查询手机是否锁定=====")
    public String isBind(@RequestParam("vMobile") String vMobile) throws DmsBizException {
        int phoneLength = 11;
        if (vMobile.length() != phoneLength) {
            logger.error("900：手机号不存在！");
            throw new DmsBizException(900, "手机号不存在！");
        }
        EmployeeDTO result = employeeService.findEmpBind(vMobile);
        String msg = "no";
        if (result != null) {
            int vState = result.getvState();
            String dtmsStatus = result.getvDTMSStatus();
            if (vState != 1 && !FLAG_ONE.equals(dtmsStatus)) {
                msg = "ok";
            } else {
                logger.error("900：该用户已锁定！");
                throw new DmsBizException(900, "该用户已锁定");
            }
        } else {
            logger.error("900：该用户已锁定！");
            throw new DmsBizException(900, "该用户已锁定");
        }
        return msg;
    }

    private void checkEmp(String vPwd, String vUser, String dtoVpwd, int vState, int nLoginFailNum, Long updateOn) throws DmsBizException {
        Long timeSlot = 0L;
        // 修改的本次登陆错误时间
        Date thisErrorLoginTime = new Date();
        //最后一次错误时间
        if (updateOn != 0) {
            Date lastLoginErrorTime = new Date(updateOn);
            timeSlot = thisErrorLoginTime.getTime() - lastLoginErrorTime.getTime();
        }
        String regEx = "^[a-zA-Z0-9]{32}$";
        String md5Pwd = MD5Util.getEncryptedPwd(vPwd);
        if (Pattern.matches(regEx, vPwd)) {
            md5Pwd = vPwd;
        }

        //锁定三十分钟解除
        if (timeSlot >= 1800000) {
            //设置成非锁定状态
            employeeService.updateLoginFailNum(vUser, 0, 0);
            vState = 0;
            nLoginFailNum = 0;
        }

        if (!md5Pwd.equals(dtoVpwd)) {
            if (vState == 2) {
                //判断最后锁定时间,30分钟之内继续锁定
                if (timeSlot < 1800000) {
                    logger.error("900：您的账户已被锁定，请\" + (30-Math.ceil((double)timeSlot/60000)) + \"分钟之后再次尝试！");
                    throw new DmsBizException(900, "您的账户已被锁定，请" + (int) (30 - Math.ceil((double) timeSlot / 60000)) + "分钟之后再次尝试！");
                } else if (timeSlot == 0) {
                    logger.error("900：您的账户已被锁定，请30分钟之后再次尝试！");
                    throw new DmsBizException(900, "您的账户已被锁定，请30分钟之后再次尝试！");
                }
            }
            if (nLoginFailNum == 4) {
                //设置成锁定状态（0：正常 1：锁定），错误次数为5
                employeeService.updateLoginFailNum(vUser, 2, 5);
                logger.error("900：您的账户已被锁定，请30分钟之后再次尝试！");
                throw new DmsBizException(900, "您的账户已被锁定，请30分钟之后再次尝试！");
            } else {
                employeeService.updateLoginFailNum(vUser, 0, nLoginFailNum + 1);
                logger.error("900：用户名或密码错误您还有" + (5 - nLoginFailNum - 1) + "次登陆机会！");
                throw new DmsBizException(900, "用户名或密码错误您还有" + (5 - nLoginFailNum - 1) + "次登陆机会！");
            }
        } else {
            //密码正确的情况如果是锁定状态
            if (vState == 2) {
                //判断最后锁定时间,30分钟之内继续锁定
                if (timeSlot < 1800000) {
                    logger.error("900：您的账户已被锁定，请\" + (30-Math.ceil((double)timeSlot/60000)) + \"分钟之后再次尝试！");
                    throw new DmsBizException(900, "您的账户已被锁定，请" + (int) (30 - Math.ceil((double) timeSlot / 60000)) + "分钟之后再次尝试！");
                }
            }
        }
        //设置成非锁定状态（0：正常 1：锁定），错误次数为0
        employeeService.updateLoginFailNum(vUser, 0, 0);
    }

    private String checkLogin(String vLogin) {

        DbUnionCommonDto searchEntity1 = new DbUnionCommonDto();
        searchEntity1.setQueryConditions("a.VLogin", 0, vLogin);
        UserDTO userdto1 = userMapper.checkUserRole(searchEntity1);


        DbUnionCommonDto searchEntity2 = new DbUnionCommonDto();
        searchEntity2.setQueryConditions("a.VLogin", 0, vLogin);
        UserDTO userdto2 = userMapper.checkUserRoleMain(searchEntity2);

        DbUnionCommonDto searchEntity3 = new DbUnionCommonDto();
        searchEntity3.setQueryConditions("a.VLogin", 0, vLogin);
        UserDTO userdto3 = userMapper.checkUserCstop(searchEntity3);

        String checkUserRole = userdto1.getCheckUserRole();

        String checkUserRoleMain = userdto2.getCheckUserRoleMain();

        String checkUserCstop = userdto3.getCheckUserCstop();

        if (!StringUtils.isNullOrEmpty(checkUserCstop) && !"0".equals(checkUserCstop)) {
            return "该用户已被停用,登录失败！";
        }

        if (StringUtils.isNullOrEmpty(checkUserRole) || "0".equals(checkUserRole)) {
            return "当前用户不存在角色，登录失败！";
        }
        if (StringUtils.isNullOrEmpty(checkUserRoleMain) || "0".equals(checkUserRoleMain)) {
            return "当前用户没有主角色 ，登录失败！";
        }

        return "OK";
    }

    /**
     * 生成验证码
     */
    @RequestMapping(value = "/getVerify", method = RequestMethod.POST)
    public RestResultResponse getVerify(@RequestBody EmployeeDTO empDto) {
        RestResultResponse res = new RestResultResponse();
        String vLogin = empDto.getvLogin();
        try {
            RandomValidateCodeUtil randomValidateCodeUtil = new RandomValidateCodeUtil();
            String[] base = randomValidateCodeUtil.getRandcode();
            redisService.set(RANDOMCODEKEY + vLogin, base[1], 300L);
            res.data(base[0]);
            res.setSuccess(true);
            res.setResultCode(200);
        } catch (Exception e) {
            logger.error("获取验证码失败！", e);
        }
        return res;
    }

    /**
     * 生成验证码
     */
    @RequestMapping(value = "/updateWXOpenId", method = RequestMethod.POST)
    @ApiOperation(value = "更新微信openID")
    public RestResultResponse updatewxopenid(@RequestBody EmployeeDTO empDto) {
        RestResultResponse res = new RestResultResponse();
        int result = 0;
        String vMobile = empDto.getvMobile();
        String openId = empDto.getvWXOpenID();
        String device = empDto.getDevice();
        EmployeeDTO dto = employeeService.findEmpInfo(vMobile);
        if (dto != null) {
            if (!"0".equals(dto.getcBindState())) {
                res.setResultCode(500);
                res.setErrMsg("用户未在DMS系统进行注册，请注册后再进行微信绑定！");
            } else if ("10011002".equals(dto.getvDTMSStatus())) {
                res.setResultCode(500);
                res.setErrMsg("您的账号在DTMS系统已经离岗！");
            } else if (dto.getvState() == 9 && "0".equals(dto.getcBindState())) {
                res.setResultCode(500);
                res.setErrMsg("该账号注册申请已经提交，请联系网管审核！");
            } else {
                if (DEVICE_APP.equals(device)) {
                    String vWXNickName = empDto.getvWXNickName();
                    result = employeeService.updateAppOpenId(vMobile, openId, vWXNickName);
                } else {
                    result = employeeService.updatewxopenid(vMobile, openId);
                }

                if (result > 0) {
                    res.setResultCode(200);
                    res.setData(openId);
                    res.setErrMsg("微信绑定成功！");
                } else {
                    res.setResultCode(500);
                    res.setErrMsg("手机号状态有误，绑定失败！");
                }
            }
        } else {
            res.setResultCode(500);
            res.setErrMsg("该DTMS账户不存在!");
        }

        return res;
    }

    private class DmsBizException extends Throwable {
        public DmsBizException(int i, String 用户名或密码不可为空) {
        }
    }

    @ApiOperation(value = "获取本经销商下人员信息（包括离职状态）",notes = "获取本经销商下人员信息（包括离职状态）",httpMethod = "GET")
    @GetMapping("/getEmployeeByUserIds")
    public List<EmployeeVO> getEmployeeByUserIds(@ApiParam(name = "userIds", value = "人员ids", required = false) @RequestParam(required = false, defaultValue = "") String userIds) {
        return employeeService.getEmployeeByUserIds(userIds);
    }
}
